//
//  GLUploadSessionManager.m
//  MaMiSchool
//
//  Created by huanggulong on 16/7/23.
//  Copyright © 2016年 历山大亚. All rights reserved.
//

#import "GLUploadSessionManager.h"
#import <AFNetworking/AFNetworking.h>
#import "GLLocalFile.h"
@interface GLUploadSessionManager()

@end

@implementation GLUploadSessionManager

static GLUploadSessionManager *_instance;

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    
    return _instance;
}

+ (instancetype)shareSessionManager
{
    if (_instance == nil) {
        _instance = [[GLUploadSessionManager alloc] init];
    }
    
    return _instance;
}


- (BOOL)uploadLocalFiles:(NSArray *)files progress:(NSProgress *)progress indexBlock:(GLCompleteIntBlock)indexBlock completeBlock:(GLCompleteIntBlock)completeBlock{
    if (self.isUpload) { //如果正在上传文件
        if (completeBlock) {
            completeBlock(0); //上传文件的东西正在被人用
        }
        return NO;
    }
    _upload = YES;
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager *session = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:config];
    session.operationQueue.maxConcurrentOperationCount = 1;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (int i = 0; i < files.count; i ++) {
            __block  BOOL flag = YES;   //某个文件是否完成上传 (success or failure)
            __block  BOOL failure = YES; //文件上传失败 退出此次上传
            GLLocalFile *file = files[i];
            if (indexBlock) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    indexBlock(i);
                });
            }
            if(file.fileKey.length > 0){
                if (file == [files lastObject]) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        completeBlock(1);
                    });
                }
                _upload = NO;
                continue;
            }
            [self uploadPostWithFile:file completion:^(NSString *url) {
                if (url == nil) {
                    flag = NO;
                    failure = YES;
                }else{
                    file.fileKey = url;
                    flag = NO;
                    failure = NO;
                }
            } progress:progress failure:^(NSError * error) {
                flag = NO;
                failure = YES;
            }];
            while (flag) { //正在上传
                sleep(0.5);
            }
            if (failure) {
                if (completeBlock) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        completeBlock(0);
                    });
                }
                _upload = NO;
                break;
            }else{
                if (file == [files lastObject]) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        completeBlock(1);
                    });
                }
                _upload = NO;
            }
        }
        
    });
    
    return YES;
}

-(void)uploadPostWithFile:(GLLocalFile *)file completion:(void (^)(NSString *url))complete progress:(NSProgress *)progress failure:(void (^)(NSError *))failure{
    NSData *data = file.fileData;
    if (data == nil) {
        if (file.fileURL.length > 0) {
            data = [NSData dataWithContentsOfFile:file.fileURL];
        }
    }
    if (data == nil) {
        NSError *error = [NSError errorWithDomain:@"org.hgl" code:1023 userInfo:@{NSLocalizedFailureReasonErrorKey:@"request FileData is nil"}];
        if (failure) {
            failure(error);
        }
        return;
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.operationQueue.maxConcurrentOperationCount = 5;
    NSError *error = nil;
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:ECUpdateURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:@"FileData" fileName:@"123.png" mimeType:@"image/png"];
        //        [formData appendPartWithFormData:data name:@"FileData"];
    } error:&error];
    if (error) {
        if (failure) {
            failure(error);
        }
        return;
    }
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    
    [[manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress != NULL) {
            (progress).completedUnitCount = uploadProgress.completedUnitCount;
            (progress).totalUnitCount = uploadProgress.totalUnitCount;
        }
        NSLog(@"%lld -- %lld",uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            if (failure) {
                failure(error);
            }
        }else{
            if (complete) {
                complete([responseObject valueForKey:@"path"]);
            }
        }
    }] resume];
    
}

@end
